﻿Imports Microsoft.Practices.Unity
Imports System.Web
Imports System.Diagnostics.Contracts

Namespace Unity
    Public Class HttpRequestLifetimeManager
        Inherits LifetimeManager
        Implements IDisposable

        Private _ItemKey As String = Guid.NewGuid.ToString()

        Public Overrides Function GetValue() As Object
            Return HttpContext.Current.Items(_ItemKey)
        End Function

        Public Overrides Sub RemoveValue()
            HttpContext.Current.Items.Remove(_ItemKey)
        End Sub

        Public Overrides Sub SetValue(newValue As Object)
            HttpContext.Current.Items(_ItemKey) = newValue
        End Sub

        <ContractInvariantMethod()>
        Private Sub ObjectInvariant()
            Contract.Invariant(Not String.IsNullOrWhiteSpace(_ItemKey), "Chiave context item non valida")
            Contract.Invariant(HttpContext.Current IsNot Nothing, "Contesto corrente nullo")
        End Sub

#Region "IDisposable Support"
        Private disposedValue As Boolean ' To detect redundant calls

        ' IDisposable
        Protected Overridable Sub Dispose(disposing As Boolean)
            If Not Me.disposedValue Then
                If disposing Then
                    HttpContext.Current.Items.Remove(_ItemKey)
                End If

                ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
                ' TODO: set large fields to null.
            End If
            Me.disposedValue = True
        End Sub

        ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
        'Protected Overrides Sub Finalize()
        '    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        '    Dispose(False)
        '    MyBase.Finalize()
        'End Sub

        ' This code added by Visual Basic to correctly implement the disposable pattern.
        Public Sub Dispose() Implements IDisposable.Dispose
            ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub
#End Region

    End Class
End Namespace